﻿using System.Collections.ObjectModel;
using System.Windows;
using MyOS.Models;
using Panuon.UI.Silver.Core;

namespace MyOS.ViewModel
{
    public class MainWindowViewModel : PropertyChangedBase
    {
        private string _searchText;

        public MainWindowViewModel()
        {
            MenuItems = new ObservableCollection<TreeViewItemModel>
            {
                new TreeViewItemModel("模拟系统信息", "VirtualInformation", "\uf17a ")
                {
                    MenuItems = new ObservableCollection<TreeViewItemModel>
                    {
                        new TreeViewItemModel("概述", "VirtualAbout", "\uf17a "),
                        new TreeViewItemModel("存储设备", "VirtualDisk",
                            "\uf1b2"),
                        new TreeViewItemModel("CPU", "VirtualCPU", "\uf2db "),
                        new TreeViewItemModel("进程", "Process", "\uf0cb "),
                        new TreeViewItemModel("命令行接口", "VirtualCommand", "\uf2d0 ")
                    }
                }
            };
        }

        public string SearchText
        {
            get => _searchText;
            set
            {
                _searchText = value;
                NotifyPropertyChanged();
                OnSearchTextChanged();
            }
        }

        public ObservableCollection<TreeViewItemModel> MenuItems { get; } =
            new ObservableCollection<TreeViewItemModel>();

        #region Event

        private void OnSearchTextChanged()
        {
            foreach (var item in MenuItems) ChangeItemVisibility(item);
        }

        private bool ChangeItemVisibility(TreeViewItemModel model)
        {
            var result = model.Header.ToLower().Contains(SearchText.ToLower());

            if (model.MenuItems.Count != 0)
                foreach (var item in model.MenuItems)
                {
                    var inner = ChangeItemVisibility(item);
                    result = result || inner;
                }

            model.Visibility = result ? Visibility.Visible : Visibility.Collapsed;
            model.IsExpanded = result;
            return result;
        }

        #endregion
    }
}